package cn.com.agree.product.service.impl;

import cn.com.agree.product.dao.ProductInfoDao;
import cn.com.agree.product.dto.CartDTO;
import cn.com.agree.product.entity.ProductInfo;
import cn.com.agree.product.enums.ProductStatusEnum;
import cn.com.agree.product.enums.ResultEnum;
import cn.com.agree.product.exception.ProductException;
import cn.com.agree.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * Descriptions...
 *
 * @author sun.ys
 * @date 2020/8/16.
 */
@Service
public class ProductServiceImpl implements ProductService {
    
    
    @Autowired
    private ProductInfoDao  productInfoDao;
    
    @Override
    public List<ProductInfo> findUpAll() {
    
        return   productInfoDao.findByProductStatus(ProductStatusEnum.UP.getCode());
       
    }
    
    @Override
    public List<ProductInfo> findList(List<String> productIdList) {
        return productInfoDao.findByProductIdIn(productIdList);
    }
    
    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
    
        for (CartDTO cartDTO : cartDTOList) {
        
            //判断商品是否存在
           Optional<ProductInfo>  productInfoOptional =  productInfoDao.findById(cartDTO.getProductId());
            if (!productInfoOptional.isPresent()) {
               
               throw  new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            
            ProductInfo productInfo = productInfoOptional.get();
           
           //库存是否足够
            Integer result = productInfo.getProductStock()- cartDTO.getProductQuantity();
            
            if (result < 0){
                throw  new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            
            productInfo.setProductStock(result);
            productInfoDao.save(productInfo);
        
        }
        
    }
}
